package cn.tx.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import cn.tx.dao.BaseDao;
import cn.tx.service.BaseService;
import cn.tx.util.ERPConstants;
import cn.tx.util.Page;

public class BaseServiceImpl<T, Q> implements BaseService<T, Q> {

   BaseDao<T, Q> baseDao;
	
  
	
	
	@Override
	public void save(T t) {
		baseDao.save(t);
	}

	@Override
	public void update(T t) {
		baseDao.update(t);
		
	}

	@Override
	public void delete(T t) {
		baseDao.delete(t);
	}

	@Override
	public T getObjectById(Object objId) {
		return baseDao.getObjectById(objId);
	}

	@Override
	public List<T> listAll() {
		return baseDao.listAll();
	}

	@Override
	public List<T> selectObjByCondition(Q q, List<String> exclude) {
		return baseDao.selectObjByCondition(q, exclude);
	}

	@Override
	public Page selectObjectByConditionPage(Q q,List<String> exclude) {
		
		//获得查询对象的具体类
		Class<? extends Object> clazz = q.getClass();
		//获得查询对象类的getPageNo的方法
		Method getPageNoMethod = null;
		try {
			getPageNoMethod = clazz.getDeclaredMethod("getPageNo", null);
		} catch (NoSuchMethodException | SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//反射的调用getPageNo方法
		Integer pageNo = null;
		try {
			pageNo = (Integer) getPageNoMethod.invoke(q, null);
		} catch (IllegalAccessException | IllegalArgumentException
				| InvocationTargetException e) {
			e.printStackTrace();
		}
		//创建page对象
		Page page = new Page(pageNo, ERPConstants.PAGE_SIZE);
		//查询分页的结果集
		List<T> list = baseDao.selectObjByConditionPage(q, page.getStartNum(), exclude );
		//当前查询条件下的记录数
		Long count = baseDao.selectObjByConditionCount(q,  exclude);
		page.setList(list);
		page.setTotalCount(count);
		return page;
	}

}
